<template>
  <el-tabs v-model="activeName" @tab-click="handleClick">
    <el-tab-pane label="经验管理" name="1">
      <hzhy-data-table ref="dataTable" v-bind="experienceTableConfig">
        <template slot="left-btn">
          <el-button type="primary" icon="el-icon-plus" plain @click="handleAdd"> 添加 </el-button>
        </template>
      </hzhy-data-table>
    </el-tab-pane>
    <el-tab-pane label="地点管理" name="2">
      <hzhy-data-table ref="dataTable" v-bind="addressTableConfig">
        <template slot="left-btn">
          <el-button type="primary" icon="el-icon-plus" plain @click="handleAdd"> 添加 </el-button>
        </template>
      </hzhy-data-table>
    </el-tab-pane>
    <el-tab-pane label="公司管理" name="3">
      <hzhy-data-table ref="dataTable" v-bind="companyTableConfig">
        <template slot="left-btn">
          <el-button type="primary" icon="el-icon-plus" plain @click="handleAdd"> 添加 </el-button>
        </template>
      </hzhy-data-table>
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import * as api from '@/const/api'

export default {
  components: {},
  props: {
    value: {
      type: [Object, String],
      default: () => {},
    },
  },
  data() {
    return {
      activeName: '1',
      editRow: '',
      experienceData: [],
      addressData: [],
      companyData: [],
      type: '',
    }
  },
  computed: {
    experienceTableConfig() {
      return {
        defaultData: this.experienceData,
        noPagination: true,
        content: 'data.data',
        columns: [
          {
            label: '序号',
            type: 'index',
            prop: 'index',
            fixed: 'left',
          },
          {
            label: '经验描述（中文）',
            prop: 'descriptionZh',
            formatter: (row) => {
              if (this.activeName !== '1' || this.editRow.id !== row.id) {
                return row.descriptionZh
              }
              return (
                <el-input
                  v-model={row.descriptionZh}
                  placeholder="请输入"
                  onChange={(e) => row.descriptionZh === e}
                ></el-input>
              )
            },
          },
          {
            label: '经验描述（英文）',
            prop: 'descriptionEn',
            formatter: (row) => {
              if (this.activeName !== '1' || this.editRow.id !== row.id) {
                return row.descriptionEn
              }
              return (
                <el-input
                  v-model={row.descriptionEn}
                  placeholder="请输入"
                  onChange={(e) => row.descriptionEn === e}
                ></el-input>
              )
            },
          },
          {
            label: '排序',
            prop: 'sort',
            formatter: (row) => {
              if (this.activeName !== '1' || this.editRow.id !== row.id) {
                return row.sort
              }
              return (
                <el-input-number
                  v-model={row.sort}
                  min={0}
                  onChange={(e) => row.sort === e}
                ></el-input-number>
              )
            },
          },
          {
            label: '操作',
            prop: 'operation',
            width: 120,
            fixed: 'right',
            setBtns: (row, index) => {
              const hideEdit =
                (this.type === 'edit' && this.editRow.id === row.id) ||
                (this.type === 'add' && !row.id)

              const btns = [
                {
                  label: '编辑',
                  hide: hideEdit,
                  handler: () => {
                    this.type = 'edit'
                    this.editRow = { ...row }
                  },
                },
                {
                  label: '保存',
                  hide: !hideEdit,
                  handler: () => {
                    this.type = 'save'
                    this.handleSave(row)
                  },
                },
                {
                  label: '取消',
                  hide: !hideEdit,
                  handler: () => {
                    this.handleCancel()
                  },
                },
                {
                  label: '删除',
                  className: 'red',
                  hide: hideEdit,
                  handler: () => {
                    this.handleRowDelete(row)
                  },
                },
              ]
              return btns
            },
          },
        ],
      }
    },
    addressTableConfig() {
      return {
        defaultData: this.addressData,
        noPagination: true,
        content: 'data.data',
        columns: [
          {
            label: '序号',
            type: 'index',
            prop: 'index',
            fixed: 'left',
          },
          {
            label: '地点（中文）',
            prop: 'placeZh',
            formatter: (row) => {
              if (this.activeName !== '2' || this.editRow.id !== row.id) {
                return row.placeZh
              }
              return (
                <el-input
                  v-model={row.placeZh}
                  placeholder="请输入"
                  onChange={(e) => row.placeZh === e}
                ></el-input>
              )
            },
          },
          {
            label: '地点（英文）',
            prop: 'placeEn',
            formatter: (row) => {
              if (this.activeName !== '2' || this.editRow.id !== row.id) {
                return row.placeEn
              }
              return (
                <el-input
                  v-model={row.placeEn}
                  placeholder="请输入"
                  onChange={(e) => row.placeEn === e}
                ></el-input>
              )
            },
          },
          {
            label: '地址（中文）',
            prop: 'addressZh',
            formatter: (row) => {
              if (this.activeName !== '2' || this.editRow.id !== row.id) {
                return row.addressZh
              }
              return (
                <el-input
                  v-model={row.addressZh}
                  placeholder="请输入"
                  onChange={(e) => row.addressZh === e}
                ></el-input>
              )
            },
          },
          {
            label: '地址（英文）',
            prop: 'addressEn',
            formatter: (row) => {
              if (this.activeName !== '2' || this.editRow.id !== row.id) {
                return row.addressEn
              }
              return (
                <el-input
                  v-model={row.addressEn}
                  placeholder="请输入"
                  onChange={(e) => row.addressEn === e}
                ></el-input>
              )
            },
          },
          {
            label: '排序',
            prop: 'sort',
            width: 160,
            formatter: (row) => {
              if (this.activeName !== '2' || this.editRow.id !== row.id) {
                return row.sort
              }
              return (
                <el-input-number
                  v-model={row.sort}
                  min={0}
                  onChange={(e) => row.sort === e}
                ></el-input-number>
              )
            },
          },
          {
            label: '操作',
            prop: 'operation',
            width: 120,
            fixed: 'right',
            setBtns: (row, index) => {
              const hideEdit =
                (this.type === 'edit' && this.editRow.id === row.id) ||
                (this.type === 'add' && !row.id)

              const btns = [
                {
                  label: '编辑',
                  hide: hideEdit,
                  handler: () => {
                    this.type = 'edit'
                    this.editRow = { ...row }
                  },
                },
                {
                  label: '保存',
                  hide: !hideEdit,
                  handler: () => {
                    this.type = 'save'
                    this.handleSave(row)
                  },
                },
                {
                  label: '取消',
                  hide: !hideEdit,
                  handler: () => {
                    this.handleCancel()
                  },
                },
                {
                  label: '删除',
                  className: 'red',
                  hide: hideEdit,
                  handler: () => {
                    this.handleRowDelete(row)
                  },
                },
              ]
              return btns
            },
          },
        ],
      }
    },
    companyTableConfig() {
      return {
        defaultData: this.companyData,
        noPagination: true,
        content: 'data.data',
        columns: [
          {
            label: '序号',
            type: 'index',
            prop: 'index',
            fixed: 'left',
          },
          {
            label: '公司名称（中文）',
            prop: 'companyNameZh',
            formatter: (row) => {
              if (this.activeName !== '3' || this.editRow.id !== row.id) {
                return row.companyNameZh
              }
              return (
                <el-input
                  v-model={row.companyNameZh}
                  placeholder="请输入"
                  onChange={(e) => row.companyNameZh === e}
                ></el-input>
              )
            },
          },
          {
            label: '公司名称（英文）',
            prop: 'companyNameEn',
            formatter: (row) => {
              if (this.activeName !== '3' || this.editRow.id !== row.id) {
                return row.companyNameEn
              }
              return (
                <el-input
                  v-model={row.companyNameEn}
                  placeholder="请输入"
                  onChange={(e) => row.companyNameEn === e}
                ></el-input>
              )
            },
          },
          {
            label: '排序',
            prop: 'sort',
            width: 160,
            formatter: (row) => {
              if (this.activeName !== '3' || this.editRow.id !== row.id) {
                return row.sort
              }
              return (
                <el-input-number
                  v-model={row.sort}
                  min={0}
                  onChange={(e) => row.sort === e}
                ></el-input-number>
              )
            },
          },
          {
            label: '操作',
            prop: 'operation',
            width: 120,
            fixed: 'right',
            setBtns: (row, index) => {
              const hideEdit =
                (this.type === 'edit' && this.editRow.id === row.id) ||
                (this.type === 'add' && !row.id)

              const btns = [
                {
                  label: '编辑',
                  hide: hideEdit,
                  handler: () => {
                    this.type = 'edit'
                    this.editRow = { ...row }
                  },
                },
                {
                  label: '保存',
                  hide: !hideEdit,
                  handler: () => {
                    this.type = 'save'
                    this.handleSave(row)
                  },
                },
                {
                  label: '取消',
                  hide: !hideEdit,
                  handler: () => {
                    this.handleCancel()
                  },
                },
                {
                  label: '删除',
                  className: 'red',
                  hide: hideEdit,
                  handler: () => {
                    this.handleRowDelete(row)
                  },
                },
              ]
              return btns
            },
          },
        ],
      }
    },
  },
  mounted() {
    this.initPage()
  },
  methods: {
    async initPage() {
      try {
        const allAjax = []

        allAjax.push(this.$axios.$post(api.careerExperienceList))
        allAjax.push(this.$axios.$post(api.careerAddressList))
        allAjax.push(this.$axios.$post(api.careerCompanyList))

        const [experienceRes, addressRes, companyRes] = await Promise.all(allAjax)

        this.experienceData = experienceRes.data
        this.addressData = addressRes.data
        this.companyData = companyRes.data
      } catch (err) {
        this.$message.error(err.message)
      }
    },
    handleAdd() {
      if (this.activeName === '1') {
        this.experienceData.push({})
      } else if (this.activeName === '2') {
        this.addressData.push({})
      } else if (this.activeName === '3') {
        this.companyData.push({})
      }
      this.type = 'add'
    },
    async handleSave(data) {
      try {
        const urlMap = {
          1: api.careerExperience,
          2: api.careerAddress,
          3: api.careerCompany,
        }

        const params = {
          ...data,
        }

        let res = ''

        if (data.id) {
          res = await this.$axios.$put(urlMap[this.activeName], params)
        } else {
          res = await this.$axios.$post(urlMap[this.activeName], params)
        }

        const { code, msg } = res
        if (+code !== 200) {
          throw new Error(msg || '操作失败')
        }

        this.$message.success('操作成功')
        this.editRow = {}
        this.type = ''
        this.initPage()
      } catch (err) {
        this.$message.error(err.message)
      }
    },
    async handleRowDelete(row) {
      let loading = ''
      try {
        const urlMap = {
          1: api.careerExperience,
          2: api.careerAddress,
          3: api.careerCompany,
        }

        const isFlag = await this.$confirm('确认删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
        if (isFlag !== 'confirm') {
          return
        }
        loading = this.$loading({
          text: 'Loading',
          spinner: 'el-icon-loading',
        })
        const { code, msg } = await this.$axios.$delete(`${urlMap[this.activeName]}/${row.id}`)
        if (+code !== 200) {
          throw new Error(msg || '操作失败')
        }
        this.$message.success('操作成功')
        this.initPage()
      } catch (err) {
        err.message && this.$message.error(err.message)
      } finally {
        loading && loading.close()
      }
    },
    handleCancel() {
      this.initPage()
      this.editRow = {}
      this.type = ''
    },
    handleClick(e) {
      this.editRow = {}
      this.type = ''
      this.activeName = e.name
    },
  },
}
</script>

<style lang="less" scoped></style>
